package com.jl.sms.userdata.IE;

import java.util.ArrayList;
import java.util.List;

import com.jl.sms.userdata.ShortMessage;
import com.jl.util.HexUtil;

public class Concatenated implements InformationElement{

	private static final int MAX_LENGTH = 140;
	private static final int MAX_Concatenated_LENGTH = 134;
	
	private byte id = 0x00;
	private ShortMessage sm;
	private List<Byte[]> list = new ArrayList<>();

	private int total;
	private static int messageReference = 0;
	private int sequenceNumber = 1;

	public Concatenated(ShortMessage sm){
		this.sm = sm;
		if(sm.value().length > MAX_LENGTH){
			total = (sm.value().length + MAX_Concatenated_LENGTH - 1) / MAX_Concatenated_LENGTH;
		}else{
			total = 1;
			list.add(wrapByteArray(sm.value()));
		}
		if(total > 1){
			byte[] all = sm.value();
			int index = 0;
			int currentLength = MAX_Concatenated_LENGTH;
			if(sm.headerLength() == 0){
				index = 0;
			}else{
				index = 1;
			}
			while(index < all.length){
				if(currentLength + index > all.length){
					currentLength = all.length - index;
				}
				byte[] one = new byte[currentLength + 6];
				putConcatenatedHeader(one, index == 1);
				System.arraycopy(all, index, one, 6, currentLength);
				index  += currentLength;
				list.add(wrapByteArray(one));
			}
			messageReference++;
		}
	}
	
	private Byte[] wrapByteArray(byte[] one) {
		Byte[] res = new Byte[one.length];
		int index = 0;
		for(byte b : one){
			res[index++] = b;
		}
		return res;
	}

	private void putConcatenatedHeader(byte[] one, boolean isFirst) {
		if(isFirst){
			one[0] = (byte) (sm.headerLength() + 5);
		}else{
			one[0] = 0x05;
		}
		one[1] = 0x00;
		one[2] = 0x03;
		one[3] = (byte) (messageReference &0xFF);
		one[4] = (byte) (total & 0xFF);
		one[5] = (byte) (sequenceNumber & 0xFF);
		sequenceNumber++;
	}

	@Override
	public byte[] value() {
		if(total == 1){
			return sm.value();
		}else{
			byte[] res = new byte[0];
			for(Byte[] one : list){
				byte[] temp = new byte[one.length];
				System.arraycopy(one, 0, temp, 0, temp.length);
				res = HexUtil.contacByteArray(res, temp);
			}
			return res;
		}
	}
	
	/**
	 * if the message is more than 1 part ,should use this method to get the value
	 * @return
	 */
	public List<Byte[]> valueList(){
		return list;
	}

	@Override
	public int headerLength() {
		if(total == 1){
			return sm.headerLength();
		}
		return sm.headerLength() + 5;
	}

	@Override
	public byte getID() {
		return this.id ;
	}
	
	public int totalNumber(){
		return this.total;
	}
	
}
